package com.lexue.articlesync.repository;

import com.lexue.articlesync.entity.PlatformAuth;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 平台认证信息数据访问接口
 */
@Repository
public interface PlatformAuthRepository extends JpaRepository<PlatformAuth, Long> {
    
    /**
     * 根据平台ID查找认证信息
     */
    List<PlatformAuth> findByPlatformId(Long platformId);
    
    /**
     * 根据平台代码查找认证信息
     */
    @Query("SELECT pa FROM PlatformAuth pa WHERE pa.platform.code = :platformCode AND pa.enabled = true")
    List<PlatformAuth> findByPlatformCode(@Param("platformCode") String platformCode);
    
    /**
     * 根据平台代码和用户标识查找认证信息
     */
    @Query("SELECT pa FROM PlatformAuth pa WHERE pa.platform.code = :platformCode AND pa.userIdentifier = :userIdentifier")
    Optional<PlatformAuth> findByPlatformCodeAndUserIdentifier(@Param("platformCode") String platformCode, @Param("userIdentifier") String userIdentifier);
    
    /**
     * 查找启用的认证信息
     */
    List<PlatformAuth> findByEnabledTrue();
    
    /**
     * 根据状态查找认证信息
     */
    List<PlatformAuth> findByStatus(PlatformAuth.AuthStatus status);
    
    /**
     * 查找过期的认证信息
     */
    @Query("SELECT pa FROM PlatformAuth pa WHERE pa.tokenExpiresAt < CURRENT_TIMESTAMP")
    List<PlatformAuth> findExpiredAuth();
    
    /**
     * 查找有效的认证信息
     */
    @Query("SELECT pa FROM PlatformAuth pa WHERE pa.enabled = true AND pa.status = 'VALID' AND (pa.tokenExpiresAt IS NULL OR pa.tokenExpiresAt > CURRENT_TIMESTAMP)")
    List<PlatformAuth> findValidAuth();
}